import secrets
from datetime import timedelta, datetime, timezone
from typing import Any

import jwt
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel

from app.config import settings
from app.schemas.base_schema import LoginAccountType, DeviceType

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="api/v1/auth/login_oauth2",
    scheme_name="Bearer",
    refreshUrl="/api/v1/auth/refresh_token_oauth2"
)

class TokenData(BaseModel):
    sub: str
    account: str
    account_type: LoginAccountType
    device_id:str
    device_type:DeviceType
    token_version:int
    auth_keys: list[str]


def create_access_token(token_data:TokenData, expires_delta: timedelta | None = None, ):
    payload = token_data.model_dump()
    if expires_delta:
        expire = datetime.now(timezone.utc) + expires_delta
    else:
        expire = datetime.now(timezone.utc) + timedelta(
            seconds=settings.ACCESS_TOKEN_EXPIRE_MINUTES
        )
    payload.update({"exp": expire})
    token = jwt.encode(payload, key=settings.SECRET_KEY, algorithm=settings.ALGORITHM)
    return token


def create_token_version():
    """生成随机整数 token版本号,每次刷新token，版本号+1"""
    return secrets.randbelow(100)

def create_refresh_token():
    """使用32位随机字符串生成刷新Token"""
    return secrets.token_urlsafe(32)

def decode_token(token: str) -> dict[str, Any]:
    return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])